<?php

namespace app\model;

use think\facade\Cache;
use think\helper\Str;
use think\Model;
use think\model\relation\HasOne;

class StationAccount extends Model
{
    public function station(): HasOne
    {
        return $this->hasOne(StationBasic::class, "id", "station_id");
    }

    public function saveData(): array
    {
        $param = request()->post();
        $count = $this->where("account", $param['account'])->when(!empty($param['id']), function ($query) use ($param) {
            $query->where("id", "<>", $param['id']);
        })->count();
        if ($count) throw new \Exception("账号已存在");
        if(empty($param['id'])){
            $pwd = setPassword("123456");
            $param['password'] = $pwd['password'];
            $param['token'] = $pwd['token'];
        }
        $this->exists(!empty($param['id']))->save($param);
        return $this->toArray();
    }

    public function lst(): array
    {
        $param = request()->param();
        $data = $this->with(['station'])->order(['create_time' => 'desc'])->paginate(['list_rows' => 30, 'page' => $param['page'] ?? 1])->toArray();
        return pageData($data);
    }

    public function login(): array
    {
        $data = request()->post();
        $account = $this->where("account", $data['account'])->find();
        if (empty($account)) throw new \Exception("账号不存在");
        if (!checkPassword($data['password'], $account['password'], $account['token'])) throw new \Exception("密码错误");
        $token = Str::random(32);
        $timer = strtotime("+7 day");
        Cache::set("station_$token", ['id' => $account['id'], 'expire_time' => $timer], $timer);
        return compact("token", "timer");
    }
}
